<?php
/**
 * 积分 记录
 */

namespace app\api\model;


use app\common\model\Model;
use think\Db;
class PointsRecord extends Model
{
    const TABLE_NAME = 'points_record';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_1;

    protected $name = self::TABLE_NAME;

    // 记录类型
    const POINTS_INVITE_LEVEL_1 = 1; //邀请的上级
    const POINTS_INVITE_LEVEL_2 =2;
    const POINTS_INVITE_LEVEL_3 = 3;
    const POINTS_REGISTER = 4; //注册
    const POINTS_SIGN_IN =5; //签到
    const POINTS_GOODS =6; //购买商品
    const POINTS_EXCHANGE =7; //兑换
    const POINTS_WITHDRAW =8; // 提现
    const POINTS_WITHDRAW_REFUND =9 ; //提现退还
    const POINTS_ORDER_CANCEL =10 ; //取消订单，扣除 积分
    const POINTS_MONTH_SIGN_IN=11;
    const POINTS_THREE_HUNDRED_DAY_SIGN_IN=12;
    const POINTS_DONATION=13; //捐赠
    const POINTS_INVITE_MASTER =100;

    //积分值
    const NUM_REGISTER_USER = 50; //注册用户 得到的积分
    const NUM_REGISTER_DESIGN=100;
    const NUM_INVITE_USER = 50; // 邀请总积分

    const NUM_INVITE_LEVEL_1 = 25; // 1/2
    const NUM_INVITE_LEVEL_2 = 12.5 ; // 1/4
    const NUM_INVITE_LEVEL_3 = 6.25 ; // 1/8
    const NUM_SIGN_IN  =1 ;//签到 积分

    const NUM_MONTH_SIGN_IN=5;//连续一个月签到，赠送积分
    const NUM_THREE_HUNDRED_DAY_SIGN_IN=100; //300 天连续签到，赠送积分
    
    public static function addRecord($user_id,$type,$item_id,$points)
    {
        $now =time();
        return  self::commonQuery(self::TABLE_NAME)->insert(
            [
               'record_user_id'=>$user_id,
               'record_type'=>$type,
               'record_item_id'=>$item_id,
               'record_points'=>$points,
               'record_addtime'=>$now,
            ],false,true);
    }
    public static function incrUserPoints($user_id,$type,$item_id,$points)
    {
        Db::startTrans();
        
        try{
            User::incrUserPoints($user_id,$points);
            $record_id = self::addRecord($user_id,$type,$item_id,$points);
        }catch (\Exception $e)
        {
            Db::rollback();
            return false;
        }
        Db::commit();
        return $record_id;
    }
    public static function consumeUserPoints($user_id,$type,$item_id,$points)
    {
        Db::startTrans();

        try{
            User::descUserPoints($user_id,$points);
            $record_id = self::addRecord($user_id,$type,$item_id,$points);
        }catch (\Exception $e)
        {
            Db::rollback();
            return false;
        }
        Db::commit();
        return $record_id;
    }
    //处理 邀请用户注册 成功后 邀请人 积分记录规则
    public static function handleInvitePoints($login_user_id,$invite_user_id)
    {

        $points_invite_level =[
            self::POINTS_INVITE_LEVEL_1,self::POINTS_INVITE_LEVEL_2,self::POINTS_INVITE_LEVEL_3
        ];
        $num_invite_points = [
            self::NUM_INVITE_LEVEL_1,self::NUM_INVITE_LEVEL_2,self::NUM_INVITE_LEVEL_3
        ];

        Db::startTrans();

        try{
            //添加 邀请记录
            $invite_chan_info = InviteRecord::addRecord($login_user_id,$invite_user_id);
            $master_id = $invite_chan_info['master_id'];
            $chan_count = count($invite_chan_info['invite_chan']);

            $count = $chan_count >= 3?3:$chan_count;
            $sum_points=0;

            if($master_id  == $invite_chan_info['invite_chan'][$count -1])
            {
                for($i=0 ; $i < $count -1 ; $i++)
                {
                    User::incrUserPoints($invite_chan_info['invite_chan'][$i],$num_invite_points[$i]);
                    self::addRecord($invite_chan_info['invite_chan'][$i],$points_invite_level[$i],$login_user_id,$num_invite_points[$i]);
                    $sum_points+=$num_invite_points[$i];
                }
                // 主账号 获取 剩余 的积分
                // 记录类型 为 邀请等级类型，没有 主账号 类型
                $master_points = self::NUM_INVITE_USER - $sum_points;
                User::incrUserPoints($master_id,$master_points);
                self::addRecord($master_id,$points_invite_level[$i],$login_user_id,$master_points);
            }else{
                for($i=0 ; $i < $count  ; $i++)
                {
                    User::incrUserPoints($invite_chan_info['invite_chan'][$i],$num_invite_points[$i]);
                    self::addRecord($invite_chan_info['invite_chan'][$i],$points_invite_level[$i],$login_user_id,$num_invite_points[$i]);
                    $sum_points+=$num_invite_points[$i];
                }
                // 主账号
                $master_points = self::NUM_INVITE_USER - $sum_points;
                User::incrUserPoints($master_id,$master_points);
                self::addRecord($master_id,self::POINTS_INVITE_MASTER,$login_user_id,$master_points);
            }
        }catch (\Exception $e)
        {
            Db::rollback();
            return false;
        }

        Db::commit();
        return true;
    }
    public static function getRecord($user_id,$record_id,$up_time,$limit=self::LIMIT)
    {
        $query = self::commonQuery(self::TABLE_NAME)
                 ->where(['record_user_id'=>$user_id,'record_addtime'=>['elt',$up_time]]);

        if($record_id > 0)
        {
            $query->where(['record_id'=>['lt',$record_id]]);
        }
        return $query->limit($limit)->order('record_addtime desc')->select();
    }
    
    public static function handleRecord($list)
    {
        $res =[];
        $cur_month=date('Ym');
        foreach ($list as $key=>$val)
        {

            $res[$key]['record_id']=$val['record_id'];
            $res[$key]['record_timestamp']=$val['record_addtime'];
            $res[$key]['record_addtime']=date('Y-m-d H:i',$val['record_addtime']);
            $record_mon = date('Ym',$val['record_addtime']);
            $res[$key]['record_mon']=$record_mon;
            
            if($cur_month == $record_mon)
            {  
                //获取 当前用户的积分数
                $month_points_info = User::getExtendInfo($val['record_user_id'],self::CACHE_EXPIRE_LEVEL_1);
                $res[$key]['record_mon_total_points']=$month_points_info['available_points'] + $month_points_info['consume_points'];
                $res[$key]['record_mon_consume_points']=$month_points_info['consume_points'];
            }else{
                //获取 历史 每月的积分数
                $month_points_info = PointsMonStatistics::getUserMonInfo($val['record_user_id'],$record_mon);
                $res[$key]['record_mon_total_points']=$month_points_info['total_points'];
                $res[$key]['record_mon_consume_points']=$month_points_info['consume_points'];
            }
            //格式化 积分数
          //  $record_points=number_format($val['record_points'],0,'','');
            $record_points=intval($val['record_points']);
            //todo:: 购买商品 兑换 提现
            switch ($val['record_type'])
            {
                case self::POINTS_INVITE_LEVEL_1:
                case self::POINTS_INVITE_LEVEL_2:
                case self::POINTS_INVITE_LEVEL_3:
                case self::POINTS_INVITE_MASTER:
                     $res[$key]['record_item']='邀请用户奖励积分';
                     $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_REGISTER:
                    $res[$key]['record_item']='注册奖励积分';
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_SIGN_IN:
                    $res[$key]['record_item']='每天签到一次';
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_GOODS:

                    $goods_info = Goods::getGoodsInfo(OrderModel::getGoodsId($val['record_item_id']),self::CACHE_EXPIRE_LEVEL_1);
                    $res[$key]['record_item']='预约商品 '.$goods_info['goods_name'];
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_EXCHANGE:
                    $exchange_info = ExchangeRecord::getRecordInfo($val['record_item_id']);
                    $prize_info = ExchangePrize::getPrizeInfo($exchange_info['record_prize_id']);
                    $res[$key]['record_item']='兑换一次'.$prize_info['prize_name'];
                    $res[$key]['record_points'] ='-'.$record_points;
                    break;
                case self::POINTS_WITHDRAW:
                    $res[$key]['record_item']='提现';
                    $res[$key]['record_points'] ='-'.$record_points;
                    break;
                case self::POINTS_WITHDRAW_REFUND:
                    $res[$key]['record_item']='提现退还';
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_ORDER_CANCEL:
                    $res[$key]['record_item']='订单取消扣除';
                    $res[$key]['record_points'] ='-'.$record_points;
                    break;
                case self::POINTS_MONTH_SIGN_IN:
                    $res[$key]['record_item']='连续签到一个月赠送';
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_THREE_HUNDRED_DAY_SIGN_IN:
                    $res[$key]['record_item']='连续签到300天赠送';
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
                case self::POINTS_DONATION:
                    $res[$key]['record_item']='捐赠积分';
                    $res[$key]['record_points'] ='-'.$record_points;
                    break;
                default:
                    $res[$key]['record_item']='';
                    $res[$key]['record_points'] ='+'.$record_points;
                    break;
            }

        }
        return $res;
    }

    public  static function getRecordInfo($item_id,$type)
    {
        return self::commonQuery(self::TABLE_NAME,self::CACHE_EXPIRE_LEVEL_4)
              ->where(['record_type'=>$type,'record_item_id'=>$item_id])
              ->find();
    }
    //捐赠积分
    public static function donatePoints($user_id,$points)
    {
        Db::startTrans();

        try{
            $user_points = User::getUserPointsForUpdate($user_id);
            if($user_points < $points)
            {
                Db::rollback();
                return ['status'=>false,'msg'=>'积分不足'];
            }
            User::descUserPoints($user_id,$points);
            $record_id =self::commonQuery('points_donation')->insert([
                'record_user_id'=>$user_id,
                'record_points'=>$points,
                'record_addtime'=>time()
            ],false,true);
            PointsRecord::addRecord($user_id,PointsRecord::POINTS_DONATION,$record_id,$points);
        }catch (\Exception $e)
        {
            Db::rollback();
            return ['status'=>false,'msg'=>$e->getMessage()];
        }
        Db::commit();
        return ['status'=>true,'msg'=>''];
    }
}